package com.atguigu.gmall.item.redissionTest;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
public class RedissionLockTest {
    @Autowired
    RedissonClient redissonClient;

    /**
     * 可重入锁
     *   :防死锁 默认30s
     *   :业务超长:自动续期 每隔1/3锁时间,自动续满期
     *   :锁原子性操作保证
     *
     * @return
     * @throws InterruptedException
     */
    @GetMapping("/lock/hello")
    public String reentrantlock() throws InterruptedException {
        //得到锁

        RLock helloLock = redissonClient.getLock("helloLock");
        //加锁,阻塞式加锁
        //helloLock.lock();
//        boolean b = helloLock.tryLock();//不阻塞,就试一下
////        if (b){
////            System.out.println("helloLock = " + helloLock);
////            Thread.sleep(1000*60);
////            //释放锁
////            helloLock.unlock();
////        }
        //等待锁5秒,得到锁10秒释放锁
        boolean b = helloLock.tryLock(5, 10, TimeUnit.SECONDS);
        if (b){
            System.out.println("helloLock = " + helloLock);
           Thread.sleep(1000*60);
           //释放锁

       }
        return "ok";

    }
}
